<?php

namespace app\client\controller;

use app\common\controller\Frontend;
use app\common\model\banxi\Grade;
use app\common\model\banxi\organization\Organization;
use app\common\service\WeAppletService;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

class Register extends Frontend
{
    protected array $noNeedLogin = ['*'];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 注册
     * @return void
     */
    public function register()
    {
        $params = $this->request->param();
        try {
            $validate = Validate::rule([
                'name' => ValidateRule::isRequire(null, '请输入孩子姓名'),
                'phone' => ValidateRule::isRequire(null, '请填写手机号码')->isMobile(null, '请填写正确的手机号码'),
                'sex' => ValidateRule::IN([1, 2], '请设置正确的性别'),
                'gradeId' => function ($value) {
                    if (empty($value)) {
                        return '请设置年级';
                    }
                    $GradeInfo = Grade::where('id', $value)->find();
                    if (empty($GradeInfo)) {
                        return '设置的年级不存在';
                    }
                    return true;
                },
                'englishScore' => ValidateRule::isRequire(null, '请填写英语分数')
                    ->isNumber(null, '请填写正确的英语分数')
                    ->gt(0, '请填写正确的英语分数'),
                'organizationId' => function ($value) {
                    if (empty($value)) {
                        return true;
                    }
                    $OrganizationInfo = Organization::where('id', $value)->find();
                    if (empty($OrganizationInfo)) {
                        return '选择的机构不存在';
                    }
                    return true;
                }
            ]);
            if (!$validate->check($params)) {
                throw new ValidateException($validate->getError());
            }
            $code = $params['code'] ?? null;
            $openid = '';
            if ($code) {
                $weAppletService = new WeAppletService();
                $openid = $weAppletService->getAppletInfo($code);
                if (!$openid) {
                    $this->fail($weAppletService->getError());
                }
            }
            $res = $this->auth->register($params, $openid);
        } catch (Exception|PDOException|ValidateException $e) {
            $this->fail($e->getMessage());
        }
        $this->ok('注册成功', $res);

    }


}